# -*- coding;utf-8 -*-
"""
File name : QuestionList2Docx.PY.PY
Program IDE : PyCharm
Create file time: 2023/6/10 8:14
File Create By Author : 朱清闯
"""
import jinja2
from docxtpl import DocxTemplate
from docxtpl import InlineImage
from docx.shared import Mm
import os
import re
from django.conf import settings
from utils.uploadfile import get_new_name


def convert_path(path: str) -> str:
    return path.replace(r'\/'.replace(os.sep, ''), os.sep)


def sort_by_type_and_order(array):
    for i in range(len(array)-1):
        for j in range(0, len(array)-i-1):
            if array[j]['type'] > array[j+1]['type'] or array[j]['type'] == array[j+1]['type'] and array[j]['order'] > array[j+1]['order']:
                array[j], array[j+1] = array[j+1], array[j]
    return array


def question_list_2_docx_order_follow(question_list, paper_information):
    content = {}
    # print("题目列表：", question_list)
    # print("试题信息：", paper_information)
    pattern_image_rule = r'([\d+]{1,}\.[\w+]{3,4})'    # 提取图片x.jpg部分的正则表达式
    choice_number = 1
    cloze_number = 1
    has_cloze = False
    has_choice = False
    choice_question_list = []
    cloze_question_list = []
    file = os.path.join(settings.FILE_ROOT, 'templates/answer_attach_question_type_sorted.docx')
    answer_position = paper_information['answer_position']
    type_sorted = paper_information['type_sorted']
    if answer_position == 'attach' and type_sorted:
        file = os.path.join(settings.FILE_ROOT, 'templates/answer_attach_question_type_sorted.docx')
        # 排序分组选择题和填空题
        question_list.sort(key=lambda x: x["type"])
    elif answer_position == 'detach' and type_sorted:
        file = os.path.join(settings.FILE_ROOT, 'templates/answer_detach_question_type_sorted.docx')
        # 排序分组选择题和填空题
        question_list.sort(key=lambda x: x["type"])
    elif answer_position == 'attach' and not type_sorted:
        file = os.path.join(settings.FILE_ROOT, 'templates/answer_attach_question_type_unsorted.docx')
    elif answer_position == 'detach' and not type_sorted:
        file = os.path.join(settings.FILE_ROOT, 'templates/answer_detach_question_type_unsorted.docx')
    tpl = DocxTemplate(file)
    # 以-为分隔符，把图片字符串转换成数组，存入各自的images和images_explain中
    # 并为每个题目添加题号
    for i in range(len(question_list)):
        question_list[i]['number'] = i+1
        if question_list[i]['pictures'] != "":
            images = question_list[i]['pictures'].split('-')
            images_inline = []
            for image in images:
                path = os.path.join(settings.BASE_DIR).replace('\\', '/') + image
                # print("图片路径：", path)
                images_inline.append(InlineImage(tpl, path, width=Mm(40)))
            question_list[i]['images'] = images_inline
        else:
            question_list[i]['images'] = []
        if question_list[i]['pictures_explain'] != "" and re.search(pattern_image_rule, question_list[i]['pictures_explain']):
            images = question_list[i]['pictures_explain'].split('-')
            images_inline = []
            for image in images:
                path = os.path.join(settings.BASE_DIR).replace('\\', '/') + image
                print("图片路径：", path)
                images_inline.append(InlineImage(tpl, path, width=Mm(40)))
            question_list[i]['images_explain'] = images_inline
        else:
            question_list[i]['images_explain'] = []
    # 如果题型排序，即选择在先填空在后，并寻找选择题和填空题的分界处，统计各题型的题量和是否包含题型
    if type_sorted:
        if question_list[0]['type'] == 2:
            choice_number = 0
            cloze_number = len(question_list)
        else:
            for i in range(len(question_list)-1):
                if question_list[i]['type'] == question_list[i+1]['type']:
                    choice_number += 1
                else:
                    break
            cloze_number = len(question_list) - choice_number
        if choice_number > 0:
            has_choice = True
        else:
            has_choice = False
        if cloze_number > 0:
            has_cloze = True
        else:
            has_cloze = False

    paper_title = paper_information["title"]
    # 将选择题和填空题分别提取到各自的列表中
    if choice_number > 0 and cloze_number > 0:
        choice_question_list = question_list[:choice_number]
        cloze_question_list = question_list[choice_number:]
    elif choice_number > 0 and cloze_number <= 0:
        choice_question_list = question_list
    elif choice_number <= 0 and cloze_number > 0:
        cloze_question_list = question_list

    # 构建字典，用于直接写入docx模板文件中
    content = {
        'question_list': question_list,
        'cloze_question_list': cloze_question_list,
        'choice_question_list': choice_question_list,
        'has_choice': has_choice,
        'has_cloze': has_cloze,
        'cloze_number': cloze_number,
        'choice_number': choice_number,
        'total_number': len(question_list),
        'paper_title': paper_title
    }
    jinja2_environment = jinja2.Environment(autoescape=True)
    tpl.render(content, jinja2_environment)
    path = os.path.join(settings.FILE_ROOT, paper_title)
    file_name = get_new_name() + '.docx'
    full_path = path + file_name
    tpl.save(full_path)
    docx_url_return = '/static/files/' + paper_title + file_name
    # docx_url = os.path.join(settings.FILE_ROOT, paper_title) + file_name
    # remove_blank_line(full_path)
    return docx_url_return
